<template>
  <div class="update-photo">
    <img :src="img" alt="" class="img" ref="img">
    <div class="toolbar">
      <div @click="$emit('close')">取消</div>
      <div @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import { updateUserPhoto } from '@/api/user'
// 导入裁剪图片文件
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
export default {
  data () {
    return {
      cropper: null
    }
  },
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  mounted () {
    this.setCrop()
  },
  methods: {
    onConfirm () {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true,
        duration: 0
      })
      try {
        this.cropper.getCroppedCanvas().toBlob(async blob => {
          const formData = new FormData()
          formData.append('photo', blob)
          const { data } = await updateUserPhoto(formData)
          this.$emit('updatePhoto', data.data.photo)
        })
        this.$toast('更新成功')
      } catch (err) {
        this.$toast('更新失败，请重试')
      }
    },
    setCrop () {
      const image = this.$refs.img
      this.cropper = new Cropper(image, {
        viewMode: 1, // 只能在画布内容区
        dragMode: 'move', // 拖动模式 move拖动画布
        aspectRatio: 1, // 截图比例
        autoCropArea: 1, // 自动截取区域
        cropBoxMovable: false, // 截图区是否可以移动
        cropBoxResizable: false, // 截图区域的缩放
        background: false, // 背景
        movable: true // 是否可以拖动画布
      })
    }
  }
}
</script>

<style lang="less" scoped>
.update-photo {
    height: 100%;
    background-color: #000;
  .img {
    max-width: 100%;
  }
  .toolbar {
      position: fixed;
      bottom: 0;
      left: 0;
      display: flex;
      width: 100%;
      padding: 20px 10px;
      box-sizing: border-box;
      justify-content: space-between;
      z-index: 2;
      color: #fff;
  }
}
</style>
